package com.eling.elcms.travel.dao.hibernate;

import com.eling.elcms.basedoc.model.PersonalInfo;
import com.eling.elcms.core.dao.hibernate.GenericDaoHibernate;
import com.eling.elcms.privilege.model.Role;
import com.eling.elcms.travel.dao.IApprovalDefineItemDao;
import com.eling.elcms.travel.model.ApprovalDefineItem;
import com.eling.elcms.travel.model.view.ApprovalDefineItemView;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class ApprovalDefineItemDaoHibernate extends GenericDaoHibernate<ApprovalDefineItem, Long> implements IApprovalDefineItemDao{

	public ApprovalDefineItemDaoHibernate() {
		super(ApprovalDefineItem.class);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ApprovalDefineItemView> queryItem(List<Long> pklist) {
		StringBuffer sql = new StringBuffer();
		sql.append("  SELECT  ");
		sql.append("  	adi.pkApprovalDefineItem,  ");
		sql.append("  	adi.version,  ");
		sql.append("  	adi.sequenceNumber,  ");
		sql.append("  	r.pkRole,  ");
		sql.append("  	r.`name` rname,  ");
		sql.append("  	p.pkPersonalInfo,  ");
		sql.append("  	p.`name` pname  ");
		sql.append("  FROM  ");
		sql.append("  	fp_approvaldefineitem adi  ");
		sql.append("  LEFT JOIN sm_role r ON adi.pkRole = r.pkRole  ");
		sql.append("  LEFT JOIN sm_user u ON adi.pkUser = u.pkUser  ");
		sql.append("  LEFT JOIN om_attendant att ON u.pkUser = att.pkCommonUser  ");
		sql.append("  LEFT JOIN bd_personalinfo p ON att.pkPersonalInfo = p.pkPersonalInfo  ");
		sql.append("  WHERE  ");
		sql.append("  	adi.pkApprovalDefineItem IN ("+StringUtils.join(pklist, ",")+")  ");
		sql.append("  ORDER BY adi.sequenceNumber,adi.pkApprovalDefineItem  ");
		List<Object[]> objList = getSession().createNativeQuery(sql.toString()).list();
		List<ApprovalDefineItemView> returnlist = new ArrayList<ApprovalDefineItemView>();
		for(Object[] o : objList){
			ApprovalDefineItemView adiv = new ApprovalDefineItemView();
			ApprovalDefineItem adi = new ApprovalDefineItem();
			adi.setPkApprovalDefineItem(o[0] == null ? null : Long.valueOf(o[0].toString()));
			adi.setSequenceNumber(o[2] == null ? 0 : Integer.valueOf(o[2].toString()));
			adi.setVersion(o[1] == null ? 0 : Integer.valueOf(o[1].toString()));
			Role role = new Role();
			role.setPkRole(o[3] == null ? null : Long.valueOf(o[3].toString()));
			role.setName(o[4] == null ? null : o[4].toString());
			adi.setApprovalRole(role);
			
			PersonalInfo p = new PersonalInfo();
			p.setPkPersonalInfo(o[5] == null ? null : Long.valueOf(o[5].toString()));
			p.setName(o[6] == null ? null : o[6].toString());
			
			adiv.setApprovalDefineItem(adi);
			adiv.setPersonalInfo(p);
			returnlist.add(adiv);
		}
		return returnlist;
	}
	
}
